/**
 * @typedef {{title:string, id:number}} DictionaryItem
 * @typedef {{name:string, items: DictionaryItem[]}} Subplate
 * @typedef {{subplates: Subplate[], items: DictionaryItem[]}} PlateDictionary
 * 
 */

const createPlateDictionary = (function () {
  /**
   * 生成一个目录项数据对应的节点
   * @param {DictionaryItem} item 目录项数据
   */
  function initItem(item) {
    const html = `<a href="${item.id}.html">${item.title}</a>`
    const $item = document.createElement('div');
    $item.className = 'dict-item';
    $item.innerHTML = html;
    return $item;
  }

  /**
   * 生成子目录对应的节点
   * @param {Subplate} subplate 子目录
   */
  function initSubplate(subplate) {

    // DOM
    const html = `
    <div class="dict-name-container">
      <div class="dict-icon opened"></div>
      <div class="dict-name">${subplate.name}</div>
    </div>
    <div class="dict-content">
    </div>`
    const $subplate = document.createElement('div');
    $subplate.className = "dict-container";
    $subplate.innerHTML = html;
    const $items = $subplate.querySelector(".dict-content");
    for (let i = 0; i < subplate.items.length; i++) {
      $items.appendChild(initItem(subplate.items[i]));
    }

    // Listener

    let opened = true;
    const $dictIcon = $subplate.querySelector(".dict-icon");
    const $dictContent = $subplate.querySelector(".dict-content");
    function toggleOpen() {
      if (opened) {
        removeClassName($dictIcon, "opened");
        addClassName($dictContent, "hidden");
      } else {
        addClassName($dictIcon, "opened");
        removeClassName($dictContent, "hidden");
      }
      opened = !opened;
    }
    $subplate.addEventListener("click", toggleOpen)
    toggleOpen()

    return $subplate
  }
  const $plateDictContent = document.querySelector("#plate-dict-content")
  /**
   * 初始化目录
   * @param {PlateDictionary} dictionary 目录
   */
  function init(dictionary) {
    dictionary.subplates.forEach((sub) =>
      $plateDictContent.appendChild(initSubplate(sub)));
    dictionary.items.forEach((item) =>
      $plateDictContent.appendChild(initItem(item)));
  }
  return init
})()